#include "stdafx.h"
#include "LuaManager.h"
#include "LuaVM.h"
#include <common.h>

#ifdef _WIN32
#pragma comment(lib, "lua5.1.lib")
#ifdef _DEBUG
#pragma comment(lib, "luabindd.lib")
#else
#pragma comment(lib, "luabind.lib")
#endif
#endif

CLuaManager::CLuaManager(void)
{
    m_pLuaState = NULL;
}

CLuaManager::~CLuaManager(void)
{
    TLuaVMPool::iterator iCur(m_listLuaVM.begin()), iEnd(m_listLuaVM.end());

    for(;iCur != iEnd; ++iCur)
    {
        delete *iCur;
    }

    if(m_pLuaState)
    {
        lua_close(m_pLuaState);
        m_pLuaState = NULL;
    }
}

bool CLuaManager::Init()
{
    m_pLuaState = luaL_newstate();
    assert(m_pLuaState);
    luaL_openlibs(m_pLuaState);
    luabind::open(m_pLuaState);
    string configure_file = utility::system::get_exe_path();
    configure_file += "/script/configure.lua";
    if (!_LoadFile(configure_file.c_str()))
        return false;
    using namespace luabind;
    return true;
}

lua_State * CLuaManager::GetLuaState()
{
    //set self as current actor for the thread
    CLuaVM * pLuaVM = GetLuaVM();
    return pLuaVM->GetLuaState();
}

bool CLuaManager::LoadFile( const char * filename )
{
    CLuaVM * pLuaVM = GetLuaVM();
    return pLuaVM->LoadFile(filename);
}

void CLuaManager::AddPath( const char * path )
{
    CLuaVM * pLuaVM = GetLuaVM();
    pLuaVM->AddPath(path);
}

bool CLuaManager::_LoadFile( const char * path )
{
    if( luaL_dofile(m_pLuaState, path) )
    {
        LOG(CRITICAL) << lua_tostring(m_pLuaState, -1);
        return false;
    }
    return true;
}

const char * CLuaManager::GetLastError()
{
    CLuaVM * pLuaVM = GetLuaVM();
    return pLuaVM->GetLastError();
}

CLuaVM * CLuaManager::GetLuaVM()
{
    TLuaVMPool::reference ref = m_listLuaVM.local();
    if (ref == NULL)
        ref = new CLuaVM(m_pLuaState);
    return ref;
}
